<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown 编辑器</title>
    <link rel="stylesheet" href="${stylesUri}">
    <!--CSS_PLACEHOLDER-->
</head>
<body>
    <div class="toolbar">
        <button data-syntax="**$1**" title="加粗">B</button>
        <button data-syntax="*$1*" title="斜体">I</button>
        <button data-syntax="# $1" title="标题1">H1</button>
        <button data-syntax="## $1" title="标题2">H2</button>
        <button data-syntax="[链接]($1)" title="链接">🔗</button>
        <button data-syntax="![alt]($1)" title="图片">🖼️</button>
        <button data-syntax="- $1" title="列表">•</button>
        <button data-syntax="> $1" title="引用">❯</button>
        <button data-syntax="```$1```" title="代码块">```</button>
        <button data-syntax="`$1`" title="代码">`</button>
        <button data-syntax="---" title="分割线">—</button>
        <!-- 新增换行符按钮 -->
        <button data-syntax="   " title="换行符">↵</button>
        <button id="clearButton">清空</button>

        <!-- 新增复制按钮（右侧对齐） -->
        <button id="copyPreview" title="复制预览内容" style="margin-left: auto">📋 复制</button>
    </div>
    <div class="container">
        <div class="editor-area">
            <textarea id="editor" placeholder="输入Markdown内容..."></textarea>
        </div>
        <div class="preview-area" id="preview"></div>
    </div>
    <!--MARKED_JS_PLACEHOLDER-->
    <script>
        (function() {
            const vscode = acquireVsCodeApi();
            const editor = document.getElementById('editor');
            const previewUpdateDelay = 300;

            // 工具栏处理
            document.querySelector('.toolbar').addEventListener('click', (e) => {
                if (e.target.tagName === 'BUTTON') {
                    const syntax = e.target.dataset.syntax;
                    insertSyntax(syntax);
                }
            });

            // 插入语法模板
            function insertSyntax(syntaxPattern) {
                const selectionStart = editor.selectionStart;
                const selectionEnd = editor.selectionEnd;
                const selectedText = editor.value.substring(selectionStart, selectionEnd);
                
                // 处理占位符 $1
                const newText = syntaxPattern.replace('$1', selectedText || '文本');
                const newCursorPos = selectionStart + newText.indexOf('文本') + 2;

                // 更新编辑器内容
                editor.value = editor.value.slice(0, selectionStart) + 
                              newText + 
                              editor.value.slice(selectionEnd);
                
                // 设置光标位置
                editor.focus();
                editor.setSelectionRange(newCursorPos, newCursorPos);
                
                // 触发输入事件更新预览
                editor.dispatchEvent(new Event('input'));
            }

            // 实时预览（带防抖）
            let timeoutId;
            editor.addEventListener('input', () => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    vscode.postMessage({
                        type: 'updatePreview',
                        content: editor.value
                    });
                }, previewUpdateDelay);
            });

            // 接收预览更新
            window.addEventListener('message', event => {
                if (event.data.type === 'updatePreview') {
                    document.getElementById('preview').innerHTML = event.data.html;
                }
            });
            // 在第一个 script 标签末尾添加（避免重复定义）
            document.getElementById('copyPreview').addEventListener('click', async () => {
                try {
                    const previewContent = document.getElementById('preview').innerHTML;
                    console.log(previewContent);
                    // 复制富文本内容
                    const blob = new Blob([previewContent], { type: 'text/html' });
                    const data = [new ClipboardItem({ 'text/html': blob })];
                    // 复制纯文本内容
                    await navigator.clipboard.writeText(data);
                    
                    // await navigator.clipboard.write(data);
                    
                    // 通过 VS Code API 显示原生提示
                    vscode.postMessage({
                        type: 'showAlert',
                        content: '内容已复制到剪贴板'
                    });
                } catch (error) {
                    vscode.postMessage({
                        type: 'showAlert',
                        content: `复制失败: ${error}`
                    });
                }
            });
            // 清空按钮
            document.getElementById('clearButton').addEventListener('click', () => {
                editor.value = '';
                editor.dispatchEvent(new Event('input'));
            });
        })();

        
    </script>
    <script src="${markedUri}"></script>
    <script>
        const vscode = acquireVsCodeApi();
        const editor = document.getElementById('editor');
        const preview = document.getElementById('preview');

        editor.addEventListener('input', (e) => {
            vscode.postMessage({
                type: 'updatePreview',
                content: e.target.value
            });
        });
    </script>
</body>
</html>